<?php
require_once("inc.admin.php");

$this_title="$vars[admin_title] &raquo; ".($_GET["type"]=="add"? __("Add Member Sale") : __("Update Member Sale"));
$page_title=$_GET["type"]=="add"? __("Add Member Sale") : __("Update Member Sale");
$list_file=$vars["file"]["admin"]["sales_list"];

if(!$pv["task"]["Sales"]){
	$errmsg="<h2>$page_title</h2>".format_err("You do not have the privilege to manage member sales.");

	print format_admin_page($errmsg, $this_title);
	exit();
}

if(!in_array($_GET["type"], array("add","edit"))){
	header("location: $this_file?type=add");
	exit();
}

if($_GET["type"]=="edit"){
	if(!$get_s["id"]){
		$errmsg="No member sale with that ID found!";
	}elseif(!@mysql_num_rows($r=mysql_query("select * from $db->purchase where id='$get_d[id]'"))){
		$errmsg="No member sale with that ID found!";
	}else{
		$r_sale=mysql_fetch_assoc($r);
		$user=get_user_detail_by_id($r_sale['uid']);
	}
}

if($errmsg){
	$errmsg="<h2>$page_title</h2>".format_err($errmsg);

	print format_admin_page($errmsg, $this_title);
	exit();
}

$r_sale_point = $vars['dbv']['sale_point'];
$r_member_sale = $vars['dbv']['member_sale'];
$r_member_sale_d = $vars['dbv']['member_sale_d'];
$r_status=array("confirmed","cancelled");
$r_status_d=array("confirmed"=>__("Confirmed"),"cancelled"=>__("Cancelled"));
$r_payment = $vars['dbv']['sale_payment'];
$r_payment_d = $vars['dbv']['sale_payment_d'];
$r_collected=$vars['dbv']['sale_collected'];
$r_collected_d=$vars['dbv']['sale_collected_d'];
$r_purchase_from=array("hq","cr");
$r_purchase_from_d = array('hq'=>__("Headquarter"),'cr'=>__("Courier"));
$t=@mysql_num_rows($r=mysql_query("select * from $db->users where is_stockist='y' and status!='terminated' order by name"));
for($i=0;$i<$t;$i++){
	$this_stockist = mysql_fetch_assoc($r);
	$r_purchase_from[($i+2)] = $this_stockist['id'];
	$r_purchase_from_d[$this_stockist['id']] = $this_stockist['id']." - ".$this_stockist['name'];
}
$r_scat[0]="";
$r_scat_d[""]=__("All categories");
$cats=get_all_subcat_by_maincat();
for($i=0,$t=count($cats);$i<$t;$i++){
	$r_scat[($i+1)]=$cats[$i]["id"];
	$r_scat_d[$cats[$i]["id"]]=$cats[$i]["c"].$cats[$i]["title"];
}
$country_code=$vars['common']['country_code'];
$country_code_t=$vars['common']['country_code_text'];
foreach($country_code_t as $code=>$cname){
 $country_code_d[$code]=__($cname);
}
$country_code_d['']=__("All");

$td_width=180;
$datetime=ndate($vars["system_date_format"]);

require_once(M_ROOT."/classes/cls_search_cat_display.php");

//#####AJAX CALL#####
//search product
if($_GET["aj"] && $_GET["search_prod"]){
	$o_searchcat = new SearchCat($post_d['catid'], $product_title = $post_d['title'], $cur_page = $post_d['page'], $item_per_page = 10);
	print $o_searchcat->display();
	exit();
}

//calculate product cost
if($_GET["aj"] && $_GET["calc_cost"]){
	$output = ajax_calc_prod_cost($post_d, $post_s);
	print $output;
	exit();
}

if($_GET["aj"] && $_GET["check_uid"]){
	if(!$r_ref=get_user_detail_by_id($post_d['uid'])){
		$ajerrmsg="Member ID '$post_s[uid]' could not be found.";
	}else{
		$ajmsg="Member ID: $post_s[uid], Name: $r_ref[name]";
	}
	$xml=array("status"=>($ajerrmsg? "2" : "1"), "msg"=>$ajmsg.$ajerrmsg);
	print format_xml($xml);
	exit();
}
//#####END AJAX CALL#####

//#####PRINT INVOICE#####
if($_GET['print_invoice']){
	$print_result = print_invoice($r_sale);
	
	print $print_result['css'].$print_result['invoice'];
	exit;
}

//#####ADD / EDIT SALES POST#####
if($_SESSION["admin_add_member_sale"] && $_POST["__req"]){
	//#####ERROR CHECK#####
	$chk_arr="_remark";
	if($post_s["collected"]=="y"){
		$chk_arr.=",_collected_date";
	}
	if($post_s["member_sale"] == 'n'){
		$chk_arr.=",_nm_name,_nm_contact";
	}
	$chk_arr=explode(",", $chk_arr);
	foreach($post_s as $f=>$v){
		if(in_array($f, $chk_arr)){
			$data[$f]=$v;
		}
	}
	$errmsg=verify_form_data("purchase", $data);
	if(!$errmsg){
		if($_GET["type"]=="add"){
			if($post_s['member_sale'] == 'y'){
				//check uid
				if(!strlen($post_s["uid"])){
					$errmsg.=__("Please provide a Member ID.")."<br />\n";
				}elseif(!$r_user=get_user_detail_by_id($post_d["uid"])){
					$errmsg.=replace_tag(__("Member ID '<%uid%>' could not be found."), array("<%uid%>"=>$post_h["uid"]))."<br />\n";
				}
			}
			//check product entry
			$i=0;
			foreach($post_d as $f=>$v){
				if(preg_match('/^e_refno_/', $f)){
					$pi=preg_replace('/e_refno_/', '', $f);
					$prods[$i]["refno"]=$v;
					$prods[$i]["refno_s"]=$post_s["e_refno_$pi"];
					$prods[$i]["qty"]=$post_d["e_qty_$pi"];
					$i++;
				}
			}
			if(!count($prods)){
				$errmsg.=__("You must provide at least one product to add a sale.")."<br />\n";
			}else{
				$prod_dbr=explode("#", $vars["dbr"]["purchase_detail"]["qty"]);
				$all_prods=array();
				for($i=0,$t=count($prods);$i<$t;$i++){
					//check for duplicate
					if(in_array($prods[$i]["refno"], $all_prods)){
						$errmsg.=replace_tag(__("Some of the same product (reference no. '<%refno%>') has been entered more than once."), array("<%refno%>"=>$prods[$i]["refno_s"]))."<br />\n";
						$i=$t;
					}else{
						//check product key in / refno / qty
						if(!strlen($prods[$i]["refno"])){
							$errmsg.=replace_tag(__("Please provide a product reference no. in the product entry box #<%x%>."), array("<%x%>"=>strval($i+1)))."<br />\n";
						}else{
							$all_prods[]=$prods[$i]["refno"];
							$this_prod=@mysql_fetch_assoc(mysql_query("select * from $db->products where refno='".$prods[$i]["refno"]."' and status='active'")) or false;
							if(!$this_prod){
								$errmsg.=replace_tag(__("Product with reference no. '<%ref%>' could not be found."), array("<%ref%>"=>$prods[$i]["refno_s"]))."<br />\n";
							}else{
								$prods[$i]["id"]=$this_prod["id"];
								$prods[$i]["prod_type"]=$this_prod["prod_type"];
								//expanded_prods for use in recording product details in a sale, expanded_prods will store all the products entered, and will expand (store)
								//each of sub-products of a jump start package, with this sub-products is stored in an array within same record of expanded_prods[index]
								$expanded_prods[$i]["id"]=$this_prod["id"];
								$expanded_prods[$i]["refno"]=$prods[$i]["refno"];
								$expanded_prods[$i]["prod_type"]=mysql_real_escape_string($this_prod["prod_type"]);
								$expanded_prods[$i]["title"]=mysql_real_escape_string($this_prod["title"]);
								$expanded_prods[$i]["bv"]=calc_package_point("bv", $this_prod["id"]);
								$expanded_prods[$i]["dp"]=calc_package_point("dp", $this_prod["id"]);
								$expanded_prods[$i]["rp"]=calc_package_point("rp", $this_prod["id"]);
								$expanded_prods[$i]["req_qty"]=$prods[$i]["qty"];
								//prods_info store all the product info, with index is the product refno
								$prods_info[$prods[$i]["refno"]]=$expanded_prods[$i];
								if($this_prod["prod_type"]=='n'){
									//update_prod_qty used below to deduct product quantity
									$update_prod_qty[$prods[$i]["refno"]]["id"]=$prods[$i]["id"];
									$update_prod_qty[$prods[$i]["refno"]]["req_qty"]+=$prods[$i]["qty"];
									$update_prod_qty[$prods[$i]["refno"]]["avai_qty"]=$this_prod["qty"];
									$update_prod_qty[$prods[$i]["refno"]]["qty_type"]=$this_prod["qty_type"];
								}elseif($this_prod["prod_type"]=='p'){
									//package-> the product within the package can be 'inactive', but cannot be absent
									$t2=@mysql_num_rows($r2=mysql_query("select j.refno from $db->package_detail j where j.pkid='$this_prod[id]' and j.pid not in (select id from $db->products where status!='deleted')"));
									if($t2 > 0){
										$nepid="";
										for($j=0;$j<$t2;$j++){
											$nepid.=($nepid? ", ": "").mysql_result($r2, $j);
										}
										$errmsg.=replace_tag(__("Some of the product(s) within the package with reference no. '<%refno%>' is not available, product(s) that is no longer available is listed below:"), array("<%refno%>"=>$this_prod["refno"]))."<br />\n<br />\n".__("Product").__(":")." $nepid<br />\n";
									}else{
										$t2=@mysql_num_rows($r2=mysql_query("select p.*, p.qty as avai_qty, j.qty as req_qty from $db->products p, $db->package_detail j where j.pkid='$this_prod[id]' and j.pid=p.id"));
										for($j=0;$j<$t2;$j++){
											$this_pck=mysql_fetch_assoc($r2);
											$expanded_prods[$i]["pck_prod"][$j]["id"]=$this_pck["id"];
											$expanded_prods[$i]["pck_prod"][$j]["refno"]=mysql_real_escape_string($this_pck["refno"]);
											$expanded_prods[$i]["pck_prod"][$j]["prod_type"]=mysql_real_escape_string($this_pck["prod_type"]);
											$expanded_prods[$i]["pck_prod"][$j]["title"]=mysql_real_escape_string($this_pck["title"]);
											$expanded_prods[$i]["pck_prod"][$j]["bv"]=$this_pck["bv"];
											$expanded_prods[$i]["pck_prod"][$j]["dp"]=$this_pck["dp"];
											$expanded_prods[$i]["pck_prod"][$j]["rp"]=$this_pck["rp"];
											$expanded_prods[$i]["pck_prod"][$j]["req_qty"]=$this_pck["req_qty"];
											$prods_info[mysql_real_escape_string($this_pck["refno"])]=$expanded_prods[$i]["pck_prod"][$j];
											$update_prod_qty[mysql_real_escape_string($this_pck["refno"])]["id"]=$this_pck["id"];
											$update_prod_qty[mysql_real_escape_string($this_pck["refno"])]["req_qty"]+=$this_pck["req_qty"]*$prods[$i]["qty"];
											$update_prod_qty[mysql_real_escape_string($this_pck["refno"])]["avai_qty"]=$this_pck["avai_qty"];
											$update_prod_qty[mysql_real_escape_string($this_pck["refno"])]["qty_type"]=$this_pck["qty_type"];
										}
									}
								}
							}
							if(!strlen($prods[$i]["qty"])){
								$errmsg.=replace_tag(__("Please provide a quantity for the product with reference no. '<%ref%>'."), array("<%ref%>"=>$prods[$i]["refno_s"]))."<br />\n";
							}elseif(!is_numeric($prods[$i]["qty"]) || $prods[$i]["qty"]<=0){
								$errmsg.=replace_tag(__("Please provide a valid quantity (numerical with value more than zero) for the product with reference no. '<%ref%>'."), array("<%ref%>"=>$prods[$i]["refno_s"]))."<br />\n";
							}elseif($prods[$i]["qty"] > $prod_dbr[6]){
								$errmsg.=replace_tag(__("Please provide a quantity in the range <%from%> to <%to%> for the product with reference no. '<%ref%>', you have provided <%x%>."), array("<%ref%>"=>$prods[$i]["refno_s"], "<%from%>"=>"1", "<%to%>"=>strval($prod_dbr[6]), "<%x%>"=>$prods[$i]["qty"]))."<br />\n";
							}
						}
					}
				}
				//check sufficient quantity in bulk
				if(!$errmsg){
					if(in_array($post_s["purchase_from"], array("hq","cr"))){
						if(false){//($result=check_sufficient_qty($prods))!==true){
							$errmsg.=$result;
						}
					}elseif($post_s["purchase_from"] && stockist_sid_found($post_d["purchase_from"])){
						$this_stockist = get_stockist_detail_by_sid($post_d['purchase_from']);
						if(($result=check_sufficient_stockist_qty($this_stockist["id"], $prods))!==true){
							if($result===false){
								$errmsg.=__("The stockist could not be found.")."<br />\n";
							}else{
								$errmsg.=$result;
							}
						}
					}
				}
			}
			//check pickup location
			if(!in_array($post_s["purchase_from"], $r_purchase_from)){
				$errmsg.=__("Please select a pickup location.")."<br />\n";
			}elseif(!in_array($post_s["purchase_from"], array("hq","cr"))){
				if(!$post_s["purchase_from"]){
					$errmsg.=__("Please select a stockist for the pickup location.")."<br />\n";
				}elseif(!$r_stockist=get_stockist_detail_by_id($post_d["purchase_from"])){
					$errmsg.=replace_tag(__("The Stockist ID: '<%sid%>' could not be found."), array("<%sid%>"=>$post_h["purchase_from"]))."<br />\n";
				}
			}
			//check payment type
			if(!in_array($post_s["payment_type"], $r_payment)){
				$errmsg.=__("Please select a payment channel.")."<br />\n";
			}
		}
		if($_GET["type"]=="add" || ($_GET["type"]=="edit" && $r_sale["status"]!="cancelled")){
			//check collected
			if(!in_array($post_s["collected"], $r_collected)){
				$errmsg.=__("Please select a collected option.")."<br />\n";
			}else{
				if($post_s["collected"]=="y"){
					if(strlen($post_s['_collected_date'])){
						$collected_date = date('Y-m-d', strtotime($post_s['_collected_date']));
					}else{
						$collected_date = ndate('Y-m-d');
					}
					if(strlen($post_s["_collected_date"]) && !verify_date($post_s["_collected_date"])){
						$errmsg.=replace_tag(__("You have entered an invalid date format for the <%field%>."), array("<%field%>"=>__("Collected Date")))."<br />\n";
					}
				}
			}
		}
		//check commission calculation date
		if($get_s['type'] == 'add'){
			/*if(strlen($post_s['cdate'])){
				$cdate = $post_s['cdate'];
				if(!verify_date($post_s['cdate'])){
					$errmsg.=__("Invalid date format in the Commission Calculation Date.")."<br />";
				}else{
					if(strtotime($post_s['cdate']) < strtotime(ndate('Y-m-d'))){
						$calc_year = date('Y', strtotime($post_s['cdate']));
						$calc_month = date('n', strtotime($post_s['cdate']));
						if(@mysql_num_rows(mysql_query("select * from $db->cron where type in ('a','s','d','p','l') and year='$calc_year' and month='$calc_month'"))){
							$errmsg.=__("The Commission Calculation Date cannot be accepted since the commission had already been calculated for the selected period.")."<br />";
						}
					}
				}
			}else{
				$cdate = ndate('Y-m-d');
			}*/
			$cdate = ndate('Y-m-d H:i:s');
		}else{
			/*if(strlen($post_s['cdate']) && !verify_date($post_s['cdate'])){
				$errmsg.=__("Invalid date format in the Commission Calculation Date.")."<br />";
			}else{
				if(strlen($post_s['cdate'])){
					$cdate = date('Y-m-d', strtotime($post_s['cdate']));
				}else{
					$cdate = ndate('Y-m-d');
				}
				$orig_year = date('Y', strtotime($r_sale['cdate']));
				$orig_month = date('n', strtotime($r_sale['cdate']));
				$orig_day = date('j', strtotime($r_sale['cdate']));
				$calc_year = date('Y', strtotime($cdate));
				$calc_month = date('n', strtotime($cdate));
				$calc_day = date('j', strtotime($cdate));
				if($cdate != date('Y-m-d', strtotime($r_sale['cdate']))){
					if(@mysql_num_rows(mysql_query("select * from $db->cron where type in ('p') and year='$orig_year' and month='$orig_month' and day='$orig_day'"))){
						$errmsg.=__("The commission for this sale had already been calculated and you cannot change the Commission Calculation Date for this sale anymore.")."<br />";
					}elseif(@mysql_num_rows(mysql_query("select * from $db->cron where type in ('p') and year='$calc_year' and month='$calc_month' and day='$calc_day'"))){
						$errmsg.=__("The Commission Calculation Date cannot be accepted since the commission had already been calculated for the selected period.")."<br />";
					}
				}
			}*/
		}
		
		//check status
		if($_GET["type"]=="edit" && $r_sale["status"]!="cancelled"){
			if(!in_array($post_s["status"], $r_status)){
				$errmsg.=__("You have selected an invalid status.")."<br />\n";
			}
		}
	}
	//check if member have enough ewallet
	if(!$errmsg){
		foreach($r_sale_point as $point_type){
			$sale_point[$point_type] = calc_prod_point($point_type, $prods);
		}
		if($_GET["type"]=="add"){
			$pwallet = '';
			if($post_s['payment_type'] == 'e'){
				$pwallet = 'ewallet';
			}elseif($post_s['payment_type'] == 'm'){
				$pwallet = 'swallet';
			}elseif($post_s['payment_type'] == 's'){
				$pwallet = 'eswallet';
			}
			if($post_s['member_sale'] == 'y'){
				if($pwallet){
					if($r_user[$pwallet] < $sale_point['dp'] + $post_s['delivery_cost']){
						$errmsg.=replace_tag(__("This member does not have sufficient <%title%> for this sale."), array("<%title%>"=>__($vars[$pwallet."_title"])))."<br />\n<br />\n".replace_tag(__("Required <%title%>:"), array("<%title%>"=>__($vars[$pwallet."_title"])))." ".number_format($sale_point['dp'] + $post_s['delivery_cost'], 2)."<br />\n".replace_tag(__("Available <%title%>:"), array("<%title%>"=>__($vars[$pwallet."_title"])))." ".number_format($r_user[$pwallet], 2)."<br />\n";
					}
				}
			}elseif($pwallet){
				$errmsg .= replace_tag(__("You cannot select payment channel as <%title%> for non-member sale."), array('<%title%>'=>__($vars[$pwallet."_title"])))."<br />";
			}
		}
	}
	//#####END ERROR CHECK#####

	//#####PREVIEW OR CONFIRM#####
	$preview = $confirm = false;
	if(!$errmsg){
		if($_GET["type"]=="add"){
			if(!$post_s["__confirm"] && !$post_s['__edit']){
				$__preview = true;
			}elseif($post_s["__confirm"]){
				$__confirm = true;
			}
		}else{
			$__confirm = true;
		}
	}

	//#####ADD TO DB#####
	if(!$errmsg && $__confirm){
		if($_GET["type"]=="add"){//add
			$stockist_sale= in_array($post_s["purchase_from"], array('hq','cr'))? "n" : "y";
			if(!in_array($post_s["purchase_from"], array('hq','cr'))){
				$collect_address=mysql_real_escape_string($r_stockist["address"].($r_stockist["address2"]? ", $r_stockist[address2]" : ""));
				$collect_city=mysql_real_escape_string($r_stockist['city']);
				$collect_zip=mysql_real_escape_string($r_stockist['zip']);
				$collect_state=mysql_real_escape_string($r_stockist['state']);
				$collect_country=mysql_real_escape_string($r_stockist['country']);
				$sid = $r_stockist['id'];
			}else{
				$sid = '';
			}
			if($post_s["sale_collected"]=='y'){
				$collected_date=strlen($post_s["_collected_date"])? $post_d["_collected_date"] : $datetime;
			}
			
			//deduct member ewallet
			if($post_s['member_sale'] == 'y' && in_array($post_s["payment_type"], array('e','m','s'))){
				$ew_updated=false;
				if(!mysql_query($sql="update $db->users set $pwallet=$pwallet-".($sale_point['dp'] + $post_s['delivery_cost'])." where id='$post_d[uid]' limit 1")){
					$ew_errmsg=replace_tag(__("Error updating the member <%title%> account, please manually update this member <%title%> account by executing SQL."), array("<%title%>"=>__($vars[$pwallet."_title"])))."<br />\n<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n";
					$ew_errlog="Error updating the member {$vars[$pwallet."_title"]} account, please manually update this member {$vars[$pwallet."_title"]} account by executing SQL.\n\nSQL: $sql\n\nError: ".mysql_error()."\n";
				}else{
					$ew_updated=true;
				}
			}
			
			//previous sales bv, before adding sales, to calculate new rank later
			$old_bv = @mysql_result($r=mysql_query("select sum(total_bv) from $db->purchase where uid='$post_d[uid]' and first_sale='y' and no_bv!='y' and status='confirmed'"), 0) or 0;
			
			//create sale record
			if($post_s['member_sale'] == 'n'){
				$nm_name = $post_d['_nm_name'];
				$nm_contact = $post_d['_nm_contact'];
				$sale_uid = '0';
			}else{
				$nm_name = '';
				$nm_contact = '';
				$sale_uid = $post_d['uid'];
			}
			$sql="insert into $db->purchase (creator, cid, member_sale, nm_name, nm_contact, uid, first_sale, no_bv, stockist_sale, sid, collect_address, collect_city, collect_zip, collect_state, collect_country, total_bv, total_dp, total_rp, delivery_cost, payment_type, collected, collected_date, status, remark, cdate, edate)
			values ('a', '$aid', '$post_d[member_sale]', '$nm_name', '$nm_contact', '$sale_uid', 'y', '".($post_s['payment_type'] == 'm'? 'y' : 'n')."', '$stockist_sale', '$sid', '$collect_address', '$collect_city', '$collect_zip', '$collect_state', '$collect_country', '$sale_point[bv]', '".$sale_point['dp']."', '".$sale_point['rp']."', '$post_d[delivery_cost]', '$post_d[payment_type]', '$post_d[collected]', '$collected_date', 'confirmed', '$post_d[_remark]', '$cdate', '$datetime')";
			if(!mysql_query($sql)){
				$sale_errmsg.=__("Error creating a new member sale. Please manually create this sale by executing SQL.")."<br />\n<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n";
				$sale_errlog.="Error creating a new member sale. Please manually create this sale by executing SQL.<br />\n<br />\nSQL: $sql\n\nError: ".mysql_error()."\n";
			}else{
				$new_sid=mysql_insert_id();
				$sale_refno = $refno = "MS" . str_pad($new_sid, $vars['refno_min_digit'], '0', STR_PAD_LEFT);
				if(!mysql_query($sql="update $db->purchase set refno='$refno' where id='$new_sid' limit 1")){
					$sale_errmsg.=__("Error recording the sale reference number. Please manually record the sale reference number by executing SQL.")."<br />\n<br />\nSQL: $sql<br />\n<br />\nError: ".mysql_error()."<br />\n";
					$sale_errlog.="Error recording the sale reference number. Please manually record the sale reference number by executing SQL.<br />\n<br />\nSQL: $sql\n\nError: ".mysql_error()."\n";
				}
				$sale_refno = $refno = $new_sid;//refno is not used yet

				//insert product details
				for($i=0,$t=count($expanded_prods);$i<$t;$i++){
					$package=$expanded_prods[$i]["prod_type"]=='p'? true : false;
					if(!mysql_query($sql="insert into $db->purchase_detail (slid, pid, prod_type, refno, title, bv, dp, rp, qty) 
					values ('$new_sid', '".$expanded_prods[$i]["id"]."', '".$expanded_prods[$i]["prod_type"]."', '".$expanded_prods[$i]["refno"]."', '".$expanded_prods[$i]["title"]."', '".$expanded_prods[$i]["bv"]."', '".$expanded_prods[$i]["dp"]."', '".$expanded_prods[$i]["rp"]."', '".$expanded_prods[$i]["req_qty"]."')")){
						$prod_detail_errmsg.=replace_tag(__("Product reference no. '<%refno%>'."), array("<%refno%>"=>StripSlashes($expanded_prods[$i]["refno"])))."<br />\nSQL: $sql<br />\nError: ".mysql_error()."<br />\n";
						$prod_detail_errlog.=replace_tag("Product reference no. '<%refno%>'.", array("<%refno%>"=>StripSlashes($expanded_prods[$i]["refno"])))."\nSQL: $sql\nError: ".mysql_error()."\n";
					}
					//insert each products detail in a package
					if($package){
						for($j=0,$t2=count($expanded_prods[$i]["pck_prod"]);$j<$t2;$j++){
							if(!mysql_query($sql="insert into $db->purchase_detail (slid, pid, pkid, prod_type, refno, title, bv, dp, rp, qty) 
							values ('$new_sid', '".$expanded_prods[$i]["pck_prod"][$j]["id"]."', '".$expanded_prods[$i]["id"]."', 'n', '".$expanded_prods[$i]["pck_prod"][$j]["refno"]."', '".$expanded_prods[$i]["pck_prod"][$j]["title"]."', '".$expanded_prods[$i]["pck_prod"][$j]["bv"]."', '".$expanded_prods[$i]["pck_prod"][$j]["dp"]."', '".$expanded_prods[$i]["pck_prod"][$j]["rp"]."', '".$expanded_prods[$i]["pck_prod"][$j]["req_qty"]."')")){
								$prod_detail_errmsg.=replace_tag(__("Product reference no. '<%refno%>' of a package with reference no. '<%pck_refno%>'."), array("<%refno%>"=>StripSlashes($expanded_prods[$i]["pck_prod"][$j]["refno"]), "<%pck_refno%>"=>StripSlashes($expanded_prods[$i]["refno"])))."<br />\nSQL: $sql<br />\nError: ".mysql_error()."<br />\n";
								$prod_detail_errlog.=replace_tag("Product reference no. '<%refno%>' of a package with reference no. '<%pck_refno%>'.", array("<%refno%>"=>StripSlashes($expanded_prods[$i]["pck_prod"][$j]["refno"]), "<%pck_refno%>"=>StripSlashes($expanded_prods[$i]["refno"])))."\nSQL: $sql\nError: ".mysql_error()."\n";
							}
						}
					}
				}

				if($post_s['member_sale'] == 'y'){
					//calculate bonus
					$bonus_result = calc_sponsor_bonus($new_sid);
					if(!$bonus_result['status']){
						$bonus_errmsg = $bonus_errlog = $bonus['errmsg'];
					}
				
					//recalculate user new rank
					$new_rank = calc_rank($post_d['uid'], $old_bv);
					if($new_rank != $r_user['rank_a']){
						$sql = "update $db->users set rank_a='$new_rank' where id='$post_d[uid]' limit 1";
						if(!mysql_query($sql)){
							$rank_errmsg.=__("Error updating the member rank, please manually update the member rank by executing SQL.")."<br /><br />SQL: $sql<br /><br />".mysql_error()."<br />";
							$rank_errlog.="Error updating the member rank while admin purchase sales for member ID#$post_s[uid], please manually update the member rank by executing SQL.\n\nSQL: $sql\n\n".mysql_error()."\n";
						}
					}
				}

				//email user
				$dprods=prepare_prod_for_display($prods);
				$formatted_prod=format_prod_display($dprods, $post_s['delivery_cost']);
				if($post_s["purchase_from"]=='hq'){
					$location = __("Headquater");
				}elseif($post_s["purchase_from"]=='cr'){
					$location = __("Courier");
				}else{
					$location = __("Stockist ID").__(":")." $post_h[purchase_from], ".__("Name").__(":")." ".$r_stockist["name"]."<br />\n$r_stockist[address]".($r_stockist["address2"]? ", ".$r_stockist["address2"] : "").($r_stockist['city']? "<br />\n$r_stockist[city]" : '').($r_stockist['zip']? "<br />\n$r_stockist[zip], " : '').($r_stockist['state']? "$r_stockist[state]" : '')."<br />\n".$country_code_d[$r_stockist["country"]];
				}
				$td_style="style='border:1px solid black; padding: 3px;'";
				$sales_info="
				<table style='width:600px; border-collapse: collapse; font-family:arial; font-size:12px;'>
					<tr>
						<td $td_style>".__("Sales ID").__(":")."</td>
						<td $td_style>$refno</td>
					</tr>".($post_s['member_sale'] == 'y'? "
					<tr>
						<td $td_style>".__("User ID").__(":")."</td>
						<td $td_style>$post_s[uid]</td>
					</tr>
					<tr>
						<td $td_style>".__("Name").__(":")."</td>
						<td $td_style>$r_user[name]</td>
					</tr>" : "
					<tr>
						<td $td_style>".__("Customer").__(":")."</td>
						<td $td_style>$post_s[_nm_name]</td>
					</tr>
					<tr>
						<td $td_style>".__("Contact").__(":")."</td>
						<td $td_style>$post_s[_nm_contact]</td>
					</tr>")."
					<tr>
						<td $td_style>".__("Date").__(":")."</td>
						<td $td_style>".date($vars["date_format"], strtotime($datetime))."</td>
					</tr>
					<tr>
						<td $td_style>".__("Order Total").__(":")."</td>
						<td $td_style>".number_format($sale_point['bv'], 2)." ".__($vars["bv_title"])." / ".number_format($sale_point['dp'] + $post_s['delivery_cost'], 2)." ".__("DP")." / ".number_format($sale_point['rp'] + $post_s['delivery_cost'], 2)." ".__("CP")."</td>
					</tr>
					<tr>
						<td $td_style>".__("Payment Type").__(":")."</td>
						<td $td_style>".$r_payment_d[$post_s["payment_type"]]."</td>
					</tr>
					<tr>
						<td $td_style>".__("Pickup Location").__(":")."</td>
						<td $td_style>".$location."</td>
					</tr>
				</table>";
				$u_sub=$vars["title"]." - ".__("Sales Created (ID: $refno)");
				$u_msg="
				<p>Dear $post_s[_name],</p>
				<p>The administrative staff of $vars[title] had just created a sale for you, details below:</p>
				$sales_info<br />\n<br />\n
				".__("Order Details:")."<br />\n<br />\n
				$formatted_prod";
				if($post_s['member_sale'] == 'y' && $post_s['_email']){
					email_user($post_s["_email"], $r_user["code"], $u_sub, $u_msg);
				}
			}
			
			//update product qty
			if(count($update_prod_qty)){
				if(in_array($post_s["purchase_from"], array("hq","cr"))){
					//update main inventory
					foreach($update_prod_qty as $refno => $detail){
						//only update product with quantity not = unlimited
						if($detail["qty_type"] == 'l'){//l - limited
							if(!mysql_query($qty_sql="update $db->products set qty=qty-".$detail["req_qty"]." where refno='$refno'")){
								$qty_errmsg.=replace_tag(__("Product reference no. '<%refno%>', quantity to deduct: <%x%>."), array("<%refno%>"=>StripSlashes($refno), "<%x%>"=>strval($qty)))."<br />\nSQL: $qty_sql<br />";
								$qty_errlog.=replace_tag("Product reference no. '<%refno%>', quantity to deduct: <%x%>.", array("<%refno%>"=>StripSlashes($refno), "<%x%>"=>strval($qty)))."\nSQL: $qty_sql\n";
							}
						}
						//create qty record
						if(!mysql_query($sql="insert into $db->prod_qty_record (pid, sid, ttype, type, qty, cdate) values ('$detail[id]', '$new_sid', 'm', 'd', '$detail[req_qty]', '$datetime')")){
							$qty_rec_errmsg.=replace_tag(__("Product reference no. '<%refno%>', quantity record to add:"), array("<%refno%>"=>StripSlashes($refno)))."<br />\nSQL: $sql<br />";
							$qty_rec_errlog.=replace_tag("Product reference no. '<%refno%>', quantity record to add:", array("<%refno%>"=>StripSlashes($refno)))."\nSQL: $sql\n";
						}
					}
				}else{
					//update stockist inventory
					foreach($update_prod_qty as $refno => $detail){
						if(!mysql_query($qty_sql="update $db->stockist_inventory set qty=qty-".$detail["req_qty"]." where sid='$r_stockist[id]' and refno='$refno'")){
							$qty_errmsg.=replace_tag(__("Product reference no. '<%refno%>', stockist quantity to deduct: <%x%>."), array("<%refno%>"=>StripSlashes($refno), "<%x%>"=>strval($qty)))."<br />\nSQL: $qty_sql<br />";
							$qty_errlog.=replace_tag("Product reference no. '<%refno%>', stockist quantity to deduct: <%x%>.", array("<%refno%>"=>StripSlashes($refno), "<%x%>"=>strval($qty)))."\nSQL: $qty_sql\n";
						}
						//create stockist qty record
						if(!mysql_query($sql="insert into $db->stck_prod_qty_record (pid, slid, sid, ttype, type, qty, cdate) values ('$detail[id]', '$new_sid', '$r_stockist[id]', 'm', 'd', '$detail[req_qty]', '$datetime')")){
							$qty_rec_errlog.=replace_tag("Product reference no. '<%refno%>', quantity record to add:", array("<%refno%>"=>StripSlashes($refno)))."\nSQL: $sql\n";
						}
					}
				}
			}
			if($qty_errmsg){
				$qty_errmsg=__("Error updating the product quantity.")." ".($post_s["purchase_from"]=="hq"? __("Please manually deduct the respective quantity for each of the product(s) below by executing SQL:") : replace_tag(__("Please manually deduct the respective quantity for each of the product(s) to this stockist ID <%sid%> by executing SQL, as below:"), array("<%sid%>"=>$r_stockist["sid"])))."<br />\n<br />\n$qty_errmsg<br />\n";
				$qty_errlog="Error updating the product quantity.".($post_s["purchase_from"]=="hq"? "Please manually deduct the respective quantity for each of the product(s) below by executing SQL:" : replace_tag("Please manually deduct the respective quantity for each of the product(s) to this stockist ID <%sid%> by executing SQL, as below:", array("<%sid%>"=>$r_stockist["sid"])))."\n\n$qty_errlog\n";
				$critical_error.=$qty_errlog;
			}
			if($qty_rec_errmsg){
				$qty_rec_errmsg=__("Error recording the product quantity transaction.")." ".($post_s["purchase_from"]=="hq"? __("Please manually add the quantity record below by executing SQL:") : replace_tag(__("Please manually add the quantity record for this stockist ID <%sid%> by executing SQL, as below:"), array("<%sid%>"=>$r_stockist["sid"])))."<br />\n<br />\n$qty_rec_errmsg<br />\n";
				$qty_rec_errlog="Error recording the product quantity transaction.".($post_s["purchase_from"]=="hq"? "Please manually add the quantity record below by executing SQL:" : replace_tag("Please manually add the quantity record for this stockist ID <%sid%> by executing SQL, as below:", array("<%sid%>"=>$r_stockist["sid"])))."\n\n$qty_rec_errlog\n";
				$critical_error.=$qty_rec_errlog;
			}
			
			//record ewallet transaction
			if($post_s['member_sale'] == 'y' && in_array($post_s["payment_type"], array('e','m','s'))){
				$descr = addslashes("Debited $vars[currency]".number_format($sale_point['dp'] + $post_s['delivery_cost'], 2)." for the sale with ID #$sale_refno");
				if(!mysql_query($sql="insert into {$vars['dbi']['prefix']}member_".$pwallet."_record (uid, type, amount, descr, cdate) values ('$post_d[uid]', 'debit', '".($sale_point['dp'] + $post_s['delivery_cost'])."', '$descr', '$datetime')")){
					$ewrec_errmsg.=replace_tag(__("Error creating the <%title%> record for this sale transaction. Please manually create this transaction by executing SQL."), array("<%title%>"=>__($vars[$pwallet.'_title'])))."<br /><br />SQL: $sql<br /><br />Error: ".mysql_error()."<br />";
					$ewrec_errlog.=replace_tag("Error creating the <%title%> record for this sale transaction. Please manually create this transaction by executing SQL.", array("<%title%>"=>__($vars[$pwallet.'_title'])))."\n\nSQL: $sql\n\nError: ".mysql_error()."\n";
				}else{
					$new_eid = mysql_insert_id();
					$refno = strtoupper(substr($pwallet, 0, 2))."D" . str_pad($new_eid, $vars['refno_min_digit'], '0', STR_PAD_LEFT);
					$last_bal = @mysql_result(mysql_query("select bal from {$vars['dbi']['prefix']}member_".$pwallet."_record where uid='$post_d[uid]' and id!=$new_eid order by id desc limit 1"), 0);
					if(!$last_bal){
						$last_bal = 0;
					}
					$last_bal -= ($sale_point['dp'] + $post_s['delivery_cost']);
					mysql_query("update {$vars['dbi']['prefix']}member_".$pwallet."_record set bal='$last_bal' where id='$new_eid' limit 1");
				}
			}
			
			//sale error message
			$msg=replace_tag(__("The new sale has been successfully created. The ID for this sale is <%id%>. The sale details are listed below."), array("<%id%>"=>"<span class='red bold'>$sale_refno</span>"))."<br />\n";
			$logstr="The new sale has been successfully created. The ID for this sale is $sale_refno (#$new_sid).";
			$excluded_fields = array('id','nm_name','nm_contact','actual_bv','actual_dp','actual_rp');
			$log_arr = mysql_fetch_assoc(mysql_query("select * from $db->purchase where id='$new_sid'"));
			if($log_arr){
				foreach($log_arr as $f => $v){
					if(!in_array($f, $excluded_fields)){
						$dbr = explode('#', $vars['dbr']['purchase'][$f]);
						$log_fields .= ($dbr[4]? $dbr[4] : $f)." = ".$v."\n";
					}
				}
				$log_fields = rtrim($log_fields, "\n");
			}
			$logstr .= "\n".$log_fields;
			if($qty_errmsg || $qty_rec_errmsg || $sale_errmsg || $prod_detail_errmsg || $rank_errmsg || $bonus_errmsg || $ew_errmsg || $ewrec_errmsg){
				$msg.="<br />\n<span class='red'>".__("However, some error(s) had occurred:")."<br />\n".
				($qty_errmsg? "<br />\n$qty_errmsg<br />\n" : "").
				($qty_rec_errmsg? "<br />\n$qty_rec_errmsg<br />\n" : "").
				($sale_errmsg? "<br />\n$sale_errmsg<br />\n" : "").
				($prod_detail_errmsg? "<br />\n".__("Some of the product(s) could not be properly linked with this sale. Please execute the respective SQL to properly insert the link, as below:")."<br />$prod_detail_errmsg<br />\n" : "").
				($rank_errmsg? "<br />\n$rank_errmsg<br />\n" : "").
				($bonus_errmsg? "<br />\n$bonus_errmsg<br />\n" : "").
				($ew_errmsg? "<br />\n$ew_errmsg<br />\n" : "").
				($ewrec_errmsg? "<br />\n$ewrec_errmsg<br />\n" : "");
				
				$critical_error="$logstr\nHowever, some error(s) had occurred:\n".
				($qty_errlog? "\n$qty_errlog\n" : "").
				($qty_rec_errlog? "\n$qty_rec_errlog\n" : "").
				($sale_errlog? "\n$sale_errlog\n" : "").
				($prod_detail_errlog? "\nSome of the product(s) could not be properly linked with this sale. Please execute the respective SQL to properly insert the link, as below:\n$prod_detail_errlog\n" : "").
				($rank_errlog? "\n$rank_errlog\n" : "").
				($bonus_errlog? "\n$bonus_errlog\n" : "").
				($ew_errlog? "\n$ew_errlog\n" : "").
				($ewrec_errlog? "\n$ewrec_errlog\n" : "");
				$logstr = '';
			}
		}else{//update
			if($r_sale["status"]=="confirmed" && $post_s["status"]=="cancelled"){
				$status_q=", status='$post_d[status]'";
			}
			if($r_sale["status"]!='cancelled'){
				$collected_q=", collected='$post_d[collected]'";
				if($post_s["collected"]=="y"){
					$collected_q.=", collected_date='".(strlen($post_s["_collected_date"])? $post_d["_collected_date"] : $datetime)."'";
				}
				if($r_sale['member_sale'] == 'n'){
					$nm_q = ", nm_name='$post_d[_nm_name]', nm_contact='$post_d[_nm_contact]'";
				}
			}
			$sql="update $db->purchase set remark='$post_d[_remark]' $nm_q $collected_q $status_q where id='$get_d[id]' limit 1";
			if(!mysql_query($sql)){
				$errmsg.=__("Error updating the sale record.")."<br />\n<br />\n".__("SQL:")." $sql<br />\n<br />\n".__("Error:")." ".mysql_error()."<br />\n";
				$critical_error.=$errmsg;
			}
			if(!$errmsg){
				//cancelled sale
				if($r_sale["status"] != "cancelled" && $post_s["status"]=="cancelled"){
					//credit back ewallet to member
					if($r_sale['member_sale'] == 'y' && in_array($r_sale["payment_type"], array('e','m','s'))){
						if($r_sale['payment_type'] == 'e'){
							$pwallet = 'ewallet';
						}elseif($r_sale['payment_type'] == 'm'){
							$pwallet = 'swallet';
						}elseif($r_sale['payment_type'] == 's'){
							$pwallet = 'eswallet';
						}
						if(!mysql_query($sql="update $db->users set $pwallet=$pwallet+".($r_sale['total_dp'] + $r_sale['delivery_cost'])." where id='$r_sale[uid]' limit 1")){
							$ew_errmsg.=replace_tag(__("Error crediting back <%x%> <%title%> to the member <%title%> account. Please manually credit <%x%> <%title%> to this member ID: <%uid%> by executing SQL:"), array("<%x%>"=>number_format($r_sale['total_dp'] + $r_sale['delivery_cost'], 2), "<%title%>"=>__($vars[$pwallet."_title"]), "<%uid%>"=>strval($r_sale["uid"])))."<br />\nSQL: $ql<br />\nError: ".mysql_error()."<br />\n";
							$ew_errlog.=replace_tag("Error crediting back <%x%> <%title%> to the member <%title%> account. Please manually credit <%x%> <%title%> to this member ID: <%uid%> by executing SQL:", array("<%x%>"=>number_format($r_sale['total_dp'] + $r_sale['delivery_cost'], 2), "<%title%>"=>$vars[$pwallet."_title"], "<%uid%>"=>strval($r_sale["uid"])))."<br />\nSQL: $ql<br />\nError: ".mysql_error()."<br />\n";
						}
						if(!mysql_query($sql="insert into {$vars['dbi']['prefix']}member_".$pwallet."_record (uid, type, amount, descr, cdate) values ('$r_sale[uid]', 'credit', '".($r_sale['total_dp'] + $r_sale['delivery_cost'])."', '".AddSlashes("Credited $vars[currency]".number_format(($r_sale['total_dp'] + $r_sale['delivery_cost']), 2)." for cancelled sale ID: $r_sale[id]")."', '$datetime')")){
							$ewrec_errmsg.=replace_tag(__("Error creating the member <%title%> record, please manually add the record by executing SQL:"), array("<%title%>"=>__($vars[$pwallet."_title"])))." $sql<br />\n<br />\nError: ".mysql_error()."<br />";
							$ewrec_errlog.=replace_tag(__("Error creating the member <%title%> record, please manually add the record by executing SQL:"), array("<%title%>"=>$vars[$pwallet."_title"]))." $sql\n\nError: ".mysql_error()."\n";
						}else{
							$new_eid = mysql_insert_id();
							$refno = strtoupper(substr($pwallet, 0, 2))."C" . str_pad($new_eid, $vars['refno_min_digit'], '0', STR_PAD_LEFT);
							$last_bal = @mysql_result(mysql_query("select bal from {$vars['dbi']['prefix']}member_".$pwallet."_record where uid='$r_sale[uid]' and id!=$new_eid order by id desc limit 1"), 0);
							if(!$last_bal){
								$last_bal = 0;
							}
							$last_bal += ($r_sale['total_dp'] + $r_sale['delivery_cost']);
							mysql_query("update {$vars['dbi']['prefix']}member_".$pwallet."_record set bal='$last_bal' where id='$new_eid' limit 1");
						}
					}

					//credit back product qty
					unset($prods_info);
					$t=@mysql_num_rows($r=mysql_query("select * from $db->purchase_detail where slid='$get_d[id]' and pkid='0'"));
					//pkid=0 to retrieve all products that is not the sub-product of a package
					for($i=0;$i<$t;$i++){
						$this_prod=mysql_fetch_assoc($r);
						if($this_prod["prod_type"]=="p"){
							$t2=@mysql_num_rows($r2=mysql_query("select * from $db->purchase_detail where slid='$get_d[id]' and pkid='$this_prod[pid]'"));
							for($j=0;$j<$t2;$j++){
								$this_pk_prod=mysql_fetch_assoc($r2);
								$prods_info[$this_pk_prod["refno"]]=$this_pk_prod;
								$prods_info[$this_pk_prod["refno"]]["id"]=$this_pk_prod["pid"];
								$add_prod_qty[mysql_real_escape_string($this_pk_prod["refno"])] += $this_pk_prod["qty"] * $this_prod["qty"];
							}
						}else{
							if(!isset($prods_info[$this_prod["refno"]])){
								$prods_info[$this_prod["refno"]]=$this_prod;
								$prods_info[$this_prod["refno"]]["id"]=$this_prod["pid"];
							}
							$add_prod_qty[mysql_real_escape_string($this_prod["refno"])] += $this_prod["qty"];
						}
					}
					if(count($add_prod_qty)){
						if($r_sale["stockist_sale"]!="y"){
							//add back main inventory
							foreach($add_prod_qty as $refno => $qty){
								$srefno=StripSlashes($refno);
								$qty_type=@mysql_fetch_assoc(mysql_query("select qty_type from $db->products where refno='$refno'"));
								if($qty_type['qty_type'] == 'l'){//limited
									if(!mysql_query($sql="update $db->products set qty=qty+$qty where refno='$refno' limit 1")){
										$qty_errmsg.=replace_tag(__("Product with reference no. '<%refno%>', quantity to add: <%qty%>."), array("<%refno%>"=>StripSlashes($refno), "<%qty%>"=>strval($qty)))."<br />\nSQL: $sql<br />\nError: ".mysql_error()."<br />\n";
										$qty_errlog.=replace_tag("Product with reference no. '<%refno%>', quantity to add: <%qty%>.", array("<%refno%>"=>StripSlashes($refno), "<%qty%>"=>strval($qty)))."\nSQL: $sql\nError: ".mysql_error()."\n";
									}
								}
								//create qty record
								if(!mysql_query($sql="insert into $db->prod_qty_record (pid, sid, ttype, type, qty, cdate) values ('{$prods_info[$srefno]["id"]}', '$r_sale[id]', 'n', 'c', '$qty', '$datetime')")){
									$qty_rec_errmsg.=replace_tag(__("Product reference no. '<%refno%>', quantity record to add:"), array("<%refno%>"=>StripSlashes($refno)))."<br />\nSQL: $sql<br />";
									$qty_rec_errlog.=replace_tag("Product reference no. '<%refno%>', quantity record to add:", array("<%refno%>"=>StripSlashes($refno)))."\nSQL: $sql\n";
								}
							}
							if($qty_errmsg){
								$qty_errmsg=__("Some of the product(s) quantity could not be added back, as below:")."<br />\n<br />\n$qty_errmsg<br />\n".__("Please add back the quantity for the above product respectively.")."<br />\n";
								$qty_errlog="Some of the product(s) quantity could not be added back, as below:\n\n$qty_errlog\nPlease add back the quantity for the above product respectively.\n";
							}
						}else{
							//add back stockist inventory
							foreach($add_prod_qty as $refno => $qty){
								$srefno=StripSlashes($refno);
								$stockist_qty=@mysql_fetch_assoc(mysql_query("select * from $db->stockist_inventory where sid='$r_sale[sid]' and refno='$refno'")) or false;
								if($stockist_qty){
									$sql="update $db->stockist_inventory set qty=qty+$qty where sid='$r_sale[sid]' and refno='$refno' limit 1";
								}else{
									$sql="insert into $db->stockist_inventory (sid, pid, refno, title, bv, dp, rp, qty) values ('$r_sale[sid]', '".$prods_info[$srefno]["id"]."', '$refno', '".mysql_real_escape_string($prods_info[$srefno]["title"])."', '".$prods_info[$srefno]["bv"]."', '".$prods_info[$srefno]["dp"]."', '".$prods_info[$srefno]["rp"]."', '$qty')";
								}
								if(!mysql_query($sql)){
									$qty_errmsg.=replace_tag(__("Product with reference no. '<%refno%>', quantity to add: <%qty%>."), array("<%refno%>"=>StripSlashes($refno), "<%qty%>"=>strval($qty)))."<br />\nSQL: $qty_sql<br />\nError: ".mysql_error()."<br />\n";
									$qty_errlog.=replace_tag("Product with reference no. '<%refno%>', quantity to add: <%qty%>.", array("<%refno%>"=>StripSlashes($refno), "<%qty%>"=>strval($qty)))."\nSQL: $qty_sql\nError: ".mysql_error()."\n";
								}
								//create qty record
								if(!mysql_query($sql="insert into $db->stck_prod_qty_record (pid, slid, sid, ttype, type, qty, cdate) values ('{$prods_info[$srefno]["id"]}', '$r_sale[id]', '$r_sale[sid]', 'n', 'c', '$qty', '$datetime')")){
									$qty_rec_errmsg.=replace_tag(__("Product reference no. '<%refno%>', quantity record to add:"), array("<%refno%>"=>StripSlashes($refno)))."<br />\nSQL: $sql<br />";
									$qty_rec_errlog.=replace_tag("Product reference no. '<%refno%>', quantity record to add:", array("<%refno%>"=>StripSlashes($refno)))."\nSQL: $sql\n";
								}
							}
							if($qty_errmsg){
								$this_stockist = get_stockist_detail_by_id($r_sale['sid']);
								$qty_errmsg=replace_tag(__("Some of the product(s) quantity could not be added back to the stockist ID: <%sid%>, as below:"), array("<%sid%>"=>strval($this_stockist["sid"])))."<br />\n<br />\n$qty_errmsg<br />\n".__("Please add back the quantity for the above product respectively to the stockist.")."<br />\n";
								$qty_errlog=replace_tag("Some of the product(s) quantity could not be added back to the stockist ID: <%sid%>, as below:", array("<%sid%>"=>strval($this_stockist["sid"])))."\n\n$qty_errlog\nPlease add back the quantity for the above product respectively to the stockist.\n";
							}
						}
					}
				}

				$msg=__("The sale record has been successfully updated.")."<br />\n";
				$logstr = "The sale record has been successfully updated. Sale ID = $r_sale[refno] (#$r_sale[id]).";
				$excluded_fields = array('id','nm_name','nm_contact','actual_bv','actual_dp','actual_rp');
				$log_arr = mysql_fetch_assoc(mysql_query("select * from $db->purchase where id='$r_sale[id]'"));
				if($log_arr){
					foreach($log_arr as $f => $v){
						if(!in_array($f, $excluded_fields)){
							$dbr = explode('#', $vars['dbr']['purchase'][$f]);
							$log_fields .= ($dbr[4]? $dbr[4] : $f)." = ".$v."\n";
						}
					}
					$log_fields = rtrim($log_fields, "\n");
				}
				$logstr .= "\n".$log_fields;
				if($ew_errmsg || $ewrec_errmsg || $qty_errmsg || $qty_rec_errmsg){
					$msg.="<br />\n<span class='red'>".__("However, some error(s) had occurred:")."<br />\n".
					($ew_errmsg? "<br />\n$ew_errmsg<br />\n" : "").
					($ewrec_errmsg? "<br />\n$ewrec_errmsg<br />\n" : "").
					($qty_errmsg? "<br />\n$qty_errmsg" : "").
					($qty_rec_errmsg? "<br />\n$qty_rec_errmsg" : "")."</span>";
					
					$critical_error=$logstr."\n\nHowever, some error(s) had occurred:\n".
					($ew_errlog? "\n$ew_errlog\n" : "").
					($ewrec_errlog? "\n$ewrec_errlog\n" : "").
					($qty_errlog? "\n$qty_errlog" : "").
					($qty_rec_errlog? "\n$qty_rec_errlog" : "");
					$logstr = '';
				}
				$r_sale=mysql_fetch_assoc(mysql_query("select * from $db->purchase where id='$get_d[id]'"));
			}
		}
	}

	//log critical error
	if($critical_error || $logstr){
		$log_code=$_GET["type"]=="add"? "a-usa" : "a-use";
		$affected_uid=$_GET["type"]=="add"? $post_d['uid'] : $r_sale["uid"];
		$extra_fields = array('slid'=>$get_s['type'] == 'add'? $new_sid : $r_sale['id']);
		if($critical_error){
			log_activity('e', 'a', $aid, 'u', $affected_uid, $log_code, $critical_error, $extra_fields);
		}elseif($logstr){
			$log_descr = $logstr;
			log_activity('a', 'a', $aid, 'u', $affected_uid, $log_code, $log_descr, $extra_fields);
		}
	}

	$msg=$msg? format_msg($msg) : "";
	$errmsg=$errmsg? format_err("There is some error(s), please correct them before continuing:<br />\n<br />\n$errmsg") : "";

	//stop after successful add
	if($_GET["type"] == 'add' && $msg){
		//set session to disallow re-submit
		$_SESSION["admin_add_member_sale"] = false;
		$msg = "<div style='width:600px;'>$msg</div>";
		$msg.="<p>".__("The sale information is listed below.")."</p>
		$sales_info<br />\n<br />\n
		".__("Order Details:")."<br />\n<br />\n
		$formatted_prod
		<p class='center'><input type='button' value=\"".__("Add New Sale")."\" onclick=\"window.location='$this_file?type=add';\">
			<input type='button' value=\"".__("Back to Sale List")."\" onclick=\"window.location='$list_file';\">
			<input type='button' name='print_invoice' value=\"".__("Print Invoice")."\" /></p>";
		//javascript
		ob_start();
		?>
<script type="text/javascript" src="<?php echo JS_URL."/get_file_gzip.php?file=".urlencode("jquery.js"); ?>"></script>
<script type="text/javascript">
jQuery(document).ready(function(j){
	j('input[@name=print_invoice]').click(function(){
		window.open('<?php echo addslashes("$this_file?print_invoice=1&type=edit&id=$new_sid"); ?>', 'print_window', 'status=1, toolbar=1, location=1, menubar=1, width=700, height=700');
	});
});
</script>
		<?php
		$jvscript = ob_get_clean();
		print format_admin_page("<h2>$page_title</h2>".$msg, $this_title, $jvscript);
		exit();
	}
}
//enable submission, only block for back button / refresh after successful add
$_SESSION["admin_add_member_sale"] = true;
//#####END MEMBER SALES POST#####

$form_fields=array("member_sale"=>"y","uid"=>"","_nm_name"=>"","_nm_contact"=>"","purchase_from"=>"hq","sid"=>"","payment_type"=>"b","delivery_cost"=>"0","collected"=>"y","_collected_date"=>ndate('Y-m-d'),"cdate"=>ndate('Y-m-d'),"status"=>"active","_remark"=>"");
foreach($form_fields as $field => $default){
	$db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
	$dis[$field]=(!$post_s["__req"]? ($_GET["type"]=="edit"? $r_sale[$db_fieldname] : $default) : $post_h[$field]);
}
$dis["payment_type"]=$_GET["type"]=="edit"? $r_sale["payment_type"] : $dis["payment_type"];
$dis["collected"]=$_GET["type"]=="edit" && $r_sale["status"]=="cancelled"? $r_sale["collected"] : $dis["collected"];
$dis["_collected_date"]=$_GET["type"]=="edit" && !$post_s['__req'] && $r_sale["collected"]=="n" && $r_sale["collected_date"]=="0000-00-00 00:00:00"? "" : date('Y-m-d', strtotime($dis["_collected_date"]));
$dis["cdate"]=$_GET["type"]=="edit"? date('Y-m-d', strtotime($dis["cdate"])) : $dis['cdate'];

if($dis["uid"]){
	if($user=get_user_detail_by_id($dis["uid"])){
		$user_text=__("Member ID").__(":")." ".$dis["uid"].__(",")." ".__("Name").__(":")." ".$user["name"];
		$user_preview_text=__(",")." ".__("Name").__(":")." ".$user["name"];
	}
}

//-----------------------------------PREVIEW------------------------------------
if($__preview){
	foreach($post_h as $p => $v){
		$form_inputfields.="<input type='hidden' name='$p' value=\"$v\" />\n";
	}

	//javascript
	ob_start();
	?>
<script type="text/javascript" src="<?php echo JS_URL."/get_file_gzip.php?file=".urlencode("jquery.js"); ?>"></script>
<script type="text/javascript">
	jQuery(document).ready(function(j){
		j('input[@name=edit_btn]').click(function(){
			j('input[@name=__confirm]').val('');
			j('input[@name=__edit]').val('1');
			j('input[@name=back_btn],input[@name=edit_btn],input[@name=submit_btn]').attr('disabled','disabled');
			j('form[@name=sale_form]').submit();
		});

		j('form[@name=sale_form]').submit(function(){
			j('input[@name=back_btn],input[@name=edit_btn],input[@name=submit_btn]').attr('disabled','disabled');
		});
	});
</script>
	<?php
	$jvscript = ob_get_clean();


	//format input row
	$display_fields=array("uid","_nm_name","_nm_contact","_collected_date","cdate","_remark");
	foreach($form_fields as $field => $default){
		if(in_array($field, $display_fields)){
			$db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
			$dbr=explode("#", $vars["dbr"]["purchase"][$db_fieldname]);
			$readonly=$textarea=false;
			if($field=="uid"){
				$extra_display=$user_preview_text;
			}elseif($field=="_collected_date" && !$dis[$field]){
				$extra_display=__("Follow system date and time.");
			}elseif($field=="cdate" && !$dis[$field]){
				$extra_display=__("Follow system date and time.");
			}else{
				$extra_display='';
			}
			$form_inputfield[$db_fieldname]="
			<tr id='".$db_fieldname."_inputrow'>
				<td width='$td_width'>".__($dbr[4]).__(":").($dbr[3]=='m'? " ".__("*") : "")."</td>
				<td>".($db_fieldname == 'remark'? nl2br($dis[$field]) : $dis[$field]).$extra_display."</td>
			</tr>";
		}
	}

	//product entry row
	$i=0;
	foreach($post_d as $f=>$v){
		if(preg_match('/^e_refno_/', $f)){
			$pi=preg_replace('/e_refno_/', '', $f);
			$e_prods[$i]["refno"]=$v;
			$e_prods[$i]["qty"]=$post_d["e_qty_$pi"];
			$i++;
		}
	}
	$dprods=prepare_prod_for_display($e_prods);
	$formatted_prod=format_prod_display($dprods, $post_s['delivery_cost']);
	$prod_entry_row="
	<tr>
		<td colspan='2'>".__("Products").__(":")."</td>
	</tr>
	<tr>
		<td colspan='2'>$formatted_prod</td>
	</tr>";
	//pickup location row
	if($post_s["purchase_from"]=='hq'){
		$location = __("Headquater");
	}elseif($post_s["purchase_from"]=='cr'){
		$location = __("Courier");
	}else{
		$location = __("Stockist ID").__(":")." $post_h[purchase_from], ".__("Name").__(":")." ".$r_stockist["name"]."<br />\n$r_stockist[address]".($r_stockist["address2"]? ", ".$r_stockist["address2"] : "").($r_stockist['city']? "<br />\n$r_stockist[city]" : '').($r_stockist['zip']? "<br />\n$r_stockist[zip], " : '').($r_stockist['state']? "$r_stockist[state]" : '')."<br />\n".$country_code_d[$r_stockist["country"]];
	}
	$purchase_from_row="
	<tr>
		<td>".__("Pickup Location").__(":")."</td>
		<td>$location</td>
	</tr>";

	$member_sales=
	"<form name='sale_form' method='post' action='$this_file?$_SERVER[QUERY_STRING]'>
	$form_inputfields
	<input type='hidden' name='__edit' />
	<input type='hidden' name='__confirm' value='1' />
	<table class='amt_table preview_table'>
		<tr class='amt_header'>
			<td colspan='2'>".__("Sales Information")."</td>
		</tr>
		<tr>
			<td>".__("Member Sale").__(":")."</td>
			<td>".$r_member_sale_d[$post_s["member_sale"]]."</td>
		</tr>".($post_s['member_sale'] == 'y'? "
		$form_inputfield[uid]" : "
		$form_inputfield[nm_name]
		$form_inputfield[nm_contact]")."
		$prod_entry_row
		$purchase_from_row
		<tr>
			<td>".__("Payment Type").__(":")."</td>
			<td>".$r_payment_d[$post_s["payment_type"]]."</td>
		</tr>
		<tr>
			<td>".__("Delivery Cost").__(":")."</td>
			<td>".number_format($post_s['delivery_cost'], 2)."</td>
		</tr>
		<tr>
			<td>".__("Collected").__(":")."</td>
			<td>".$r_collected_d[$post_s["collected"]]."</td>
		</tr>
		$form_inputfield[collected_date]
		$form_inputfield[remark]
	</table>
	<table class='amt_table'>
		<tr>
			<td colspan='2' class='center' style='padding:20px 0 20px 0;'>
			<input type='button' value='".__("Back")."' name='back_btn' onclick=\"location='$post_[back_url]';\">&nbsp;&nbsp;&nbsp;
			<input type='button' value='".__("Edit Sales")."' name='edit_btn' />&nbsp;&nbsp;&nbsp;
			<input type='submit' name='submit_btn' value=\"".($_GET["type"]=="edit"? __("Update Member Sale") : __("Add Member Sale"))."\" />
			</td>
		</tr>
	</table>
	</form>";

//-----------------------------FIRST TIME / EDITING-----------------------------
}else{
	$member_sale_select=$_GET["type"]=="edit"? $r_member_sale_d[$dis["member_sale"]] : build_select($r_member_sale, $r_member_sale_d, $dis["member_sale"], "member_sale", $inputbox_style);
	$payment_type_select=$_GET["type"]=="edit"? $r_payment_d[$dis["payment_type"]] : build_select($r_payment, $r_payment_d, $dis["payment_type"], "payment_type", $inputbox_style);
	$purchase_from_select = build_select($r_purchase_from, $r_purchase_from_d, $dis['purchase_from'], 'purchase_from', $inputbox_style);
	$collected_select=$_GET["type"]=="edit" && $r_sale["status"]=="cancelled"? $r_collected_d[$dis["collected"]] : build_select($r_collected, $r_collected_d, $dis["collected"], "collected", $inputbox_style);
	$status_select=$_GET["type"]=="edit" && $r_sale["status"]=="cancelled"? "<input type='hidden' name='status' value=\"$r_sale[status]\" />".$r_status_d[$r_sale["status"]] : build_select($r_status, $r_status_d, $dis["status"], "status", $inputbox_style);
	
	//get the product items from post / 1st time edit a package
	if($_GET["type"]=="add" && $post_s["__req"] && !$msg){
		$i=0;
		foreach($post_s as $f => $v){
			if(preg_match('/^e_refno_[0-9]+/', $f)){
				$pi=preg_replace('/e_refno_/', '', $f);
				$e_prods[$i]["refno"]=$v;
				$e_prods[$i]["qty"]=$post_d["e_qty_$pi"];
				$i++;
			}
		}
	}
	unset($prod_list);
	for($i=0,$t=count($e_prods);$i<$t;$i++){
		$prod_list.="
		<tr class='ppl_body' id='refno_row_$i'>
			<td><a href='#' name='del_prod' rel='$i'><img src='".M_URL."/images/icons/delete.png' /></a></td>
			<td><input type='text' name='e_refno_$i' value=\"{$e_prods[$i]['refno']}\" style='width:100%;' /></td>
			<td><input type='text' name='e_qty_$i' id=\"pq_input_$i\" value=\"{$e_prods[$i]['qty']}\" style='width:100%;' /></td>
		</tr>";
		$added_refno_js.="
		added_refno[$i] = '".addslashes($e_prods[$i]['refno'])."';";
	}
	$next_prod_entry_index=$i;

	//javascript
	ob_start();
	?>
<script type="text/javascript" src="<?php echo JS_URL."/get_file_gzip.php?file=".urlencode("jquery.js,jquery.livequery.js,jquery.datepicker.js,fn/fn_in_array.js,fn/fn_array_flip.js"); ?>"></script>
<script type="text/javascript">
var prod_index = <?php echo $next_prod_entry_index; ?>;
jQuery(document).ready(function(j){
	j('form[@name=sale_form]').submit(function(){
		j('input[@name=submit_btn]').attr('disabled','disabled');
	});

	<?php # member / non-member sale change ?>
	j('select[@name=member_sale]').change(function(){
		if(j('select[@name=member_sale] > option:selected').val() == 'y'){
			j('div#member_sale_y').show();
			j('div#member_sale_n').hide();
		}else{
			j('div#member_sale_y').hide();
			j('div#member_sale_n').show();
		}
	});
	
	<?php # check user ?>
	j('input#check_uid_btn').click(function(){
		j('span#user_text').html('').removeClass('red');
		if(j('input[@name=uid]').val()==''){
			j('span#user_text').html('<?php echo addslashes(__("Please provide a Member ID!")); ?>').addClass('red');
		}else{
			j(this).attr('disabled','disabled');
			j.ajax({
				url: '<?php echo "$this_file?aj=1&type=$get_s[type]".($get_s["type"]=="edit"? "&id=$get_s[id]" : "")."&check_uid=1"; ?>',
				data: {'uid': j('input[@name=uid]').val()},
				type: 'post',
				dataType: 'xml',
				error: function(){
					j('span#user_text').html('<?php echo addslashes(__("Error checking...")); ?>').addClass('red');
				},
				success: function(data){
					var mesg='';
					if(j('loggedout', data).text()=='loggedout'){
						mesg='<?php echo addslashes(__("You have been logged out.")); ?>';
					}else{
						j(data).find('msg').each(function(){
							mesg+=j(this).text()+' ';
						});
					}
					var status=j(data).find('status').text();
					j('span#user_text').html(mesg).addClass(status==1? 'bold' : 'red');
				},
				complete: function(){
					j('input#check_uid_btn').attr('disabled','');
				}
			});
		}
	});

	<?php #add new product ?>
	var added_refno = new Array();
	<?php echo $added_refno_js; ?>
	j('a[@name=add_prod]').livequery('click', function(){
		var refno = j(this).attr('rel');
		if(in_array(refno, added_refno)){
			refarr = array_flip(added_refno);
			refi = refarr[refno];
			j('input#pq_input_'+refi).val(parseInt(j('input#pq_input_'+refi).val()) + 1);
		}else{
			j('table#pprod-list').append('<tr class="ppl_body" id="refno_row_'+prod_index+'"><td><a href="#" name="del_prod" rel="'+prod_index+'"><img src="<?php echo M_URL."/images/icons/delete.png"; ?>" /></a></td><td><input type="text" name="e_refno_'+prod_index+'" value="'+refno+'" style="width:100%;" /></td><td><input type="text" name="e_qty_'+prod_index+'" id="pq_input_'+prod_index+'" value="1" style="width:100%;" /></td></tr>');
			added_refno[prod_index] = refno;
			prod_index++;
		}
		return false;
	});
	
	<?php #delete a product ?>
	j('a[@name=del_prod]').livequery('click', function(){
		var refi = j(this).attr('rel');
		j('tr#refno_row_'+refi).remove();
		added_refno[refi] = '';
		return false;
	});
	
	<?php #page nav ?>
	j('p#pml_pagelinks > a').livequery('click', function(){
		var page = j(this).text();
		var catid = j('select[@name=category_id] > option:selected').val();
		var title = j('input[@name=prod_search]').val();
		prod_search(catid, title, page);
		return false;
	});
	
	j('input[@name=btn_prod_search]').click(function(){
		var catid = j('select[@name=category_id] > option:selected').val();
		var title = j('input[@name=prod_search]').val();
		prod_search(catid, title, 1);
	});
	
	function prod_search(catid, title, page){
		j('div#prod_search_div').html('<?php echo addslashes(__("Searching"))."..."; ?>').removeClass('red');
		j.ajax({
			url: '<?php echo "$this_file?aj=1&type=$get_s[type]".($get_s["type"]=="edit"? "&id=$get_s[id]" : "")."&search_prod=1"; ?>',
			data: {'catid': catid, 'title': title, 'page': page},
			type: 'post',
			dataType: 'html',
			error: function(){
				j('div#prod_search_div').html('<?php echo AddSlashes(__("Error searching...")); ?>').addClass('red');
			},
			success: function(data){
				var mesg='';
				var status='';
				if(j('loggedout', data).text()=='loggedout'){
					mesg='<?php echo AddSlashes(__("You have been logged out.")); ?>';
					status=2;
				}else{
					mesg=data;
				}
				j('div#prod_search_div').html(mesg).addClass(status==2? 'red' : '');
			},
			complete: function(){
			}
		});
	}
	
	<?php # calculate product cost ?>
	j('input[@name=calc_prod_cost]').click(function(){
		j('div#prod_cost').html('<?php echo addslashes(__("Calculating"))."..."; ?>').removeClass('red');
		var ref_qs = '', qty = '', refno = '';
		for(pi in added_refno){
			if (added_refno[pi] != ''){
				qty = j('input#pq_input_'+pi).val();
				refno = j('input[@name=e_refno_'+pi+']').val();
				ref_qs += '&refno'+pi+'='+refno+'&qty'+pi+'='+qty;
			}
		}
		ref_qs += '&delivery_cost='+j('input[@name=delivery_cost]').val();
		j.ajax({
			url: '<?php echo "$this_file?aj=1&type=$get_s[type]".($get_s["type"]=="edit"? "&id=$get_s[id]" : "")."&calc_cost=1"; ?>',
			data: ref_qs,
			type: 'post',
			dataType: 'html',
			error: function(){
				j('div#prod_cost').html('<?php echo AddSlashes(__("Error calculating...")); ?>').addClass('red');
			},
			success: function(data){
				var mesg='';
				var status='';
				if(j('loggedout', data).text()=='loggedout'){
					mesg='<?php echo AddSlashes(__("You have been logged out.")); ?>';
					status=2;
				}else{
					mesg=data;
				}
				j('div#prod_cost').html(mesg).addClass(status==2? 'red' : '');
			},
			complete: function(){
			}
		});
	});
	
	<?php #datepicker ?>
	j('input[@name=_collected_date]').datepicker({
		changeMonth: true,
		changeYear: true,
		dateFormat: 'yy-mm-dd',
		minDate: new Date(2009,6,1), 
		maxDate: '+1M +10D'
	});
	j('input[@name=cdate]').datepicker({
		changeMonth: true,
		changeYear: true,
		dateFormat: 'yy-mm-dd',
		minDate: new Date(2009,6,1), 
		maxDate: '+1M +10D'
	});
	
	<?php #print invoice ?>
	j('input[@name=print_invoice]').click(function(){
		window.open('<?php echo addslashes("$this_file?print_invoice=1&type=edit&id=$get_s[id]"); ?>', 'print_window', 'status=1, toolbar=1, location=1, menubar=1, width=700, height=700');
	});
});
</script>
	<?php
	$jvscript = ob_get_clean();

	//css
	ob_start();
	?>
<link rel="stylesheet" href="<?php echo CSS_URL; ?>/jstheme/ui-lightness/jquery-ui.css" type="text/css" />
	<?php
	$css .= ob_get_contents();
	ob_end_clean();

	//back button
	$url_referer=$_SERVER["HTTP_REFERER"];
	if($post_s["back_url"]){
		$back_url=$post_s["back_url"];
	}elseif($url_referer && !strstr($url_referer, $this_file)){
		$back_url=$url_referer;
	}else{
		$back_url=$list_file;
	}

	//format input row
	$display_fields=array("uid","_nm_name","_nm_contact","delivery_cost","_collected_date","cdate","_remark");
	foreach($form_fields as $field => $default){
		if(in_array($field, $display_fields)){
			$db_fieldname=preg_match('/^_/', $field)? substr($field, 1) : $field;
			$dbr=explode("#", $vars["dbr"]["purchase"][$db_fieldname]);
			$readonly=$textarea=false;
			if($field=="uid" && $_GET["type"]=="add"){
				$extra_display="<br />\n<span id='user_text'>$user_text</span><input type='button' id='check_uid_btn' value='Check Member' />";
			}elseif($field=="_collected_date"){
				$extra_display="<br />\n".__("The date and time the product(s) is collected by the member.")." ".__("Date Format:")." YYYY-MM-DD, ".__("Leave blank to use current date and time.");
			}elseif($field=="cdate"){
				$extra_display="<br />\n".__("Commission calculation date. You can only choose a date in which the commission has not been calculated yet, so that this sale commission will be calculated according to your specified date. Leave blank to use current system date and time.");
			}else{
				$extra_display='';
			}
			if($field=='uid' && $get_s['type'] == 'edit'){
				$user = get_user_detail_by_id($r_sale['uid']);
				$readonly_extra_display = ", $user[name]";
			}else{
				$readonly_extra_display = '';
			}
			if(in_array($field, array("_remark"))){
				$textarea=true;
			}
			if($_GET["type"]=="edit" && in_array($field, array("uid","sid","delivery_cost"))){
				$readonly=true;
			}elseif($_GET["type"]=="edit" && $r_sale["status"]=="cancelled" && in_array($field, array("cdate","_collected_date"))){
				$readonly=true;
			}
			$readonly_str=$readonly? "readonly='readonly'" : "";
			$form_inputfield[$db_fieldname]="
			<tr id='".$db_fieldname."_inputrow'>
				<td width='$td_width'>".__($dbr[4]).__(":").(!$readonly && $dbr[3]=='m'? " ".__("*") : "")."</td>
				<td>".($readonly? "<input type='hidden' name='$field' value=\"$dis[$field]\" />".$dis[$field].$readonly_extra_display : ($textarea? "<textarea name='$field' rows='6' $inputbox_style $readonly_str>".$dis[$field]."</textarea>" : "
				<input type='text' name='$field' $inputbox_style value=\"".$dis[$field]."\" $readonly_str />"))."$extra_display</td>
			</tr>";
		}
	}

	//product entry row
	if($_GET["type"]=="edit"){
		$dprods=prepare_prod_for_display_from_msid($get_d['id']);
		$formatted_prod=format_prod_display($dprods, $r_sale['delivery_cost']);
		$prod_entry_row="
		<tr id='prod_entry_inputrow'>
			<td colspan='2'>".__("Products").__(":")."</td>
		</tr>
		<tr>
			<td colspan='2'>$formatted_prod</td>
		</tr>";
	}else{
		//product search
		$cat_select = build_select($r_scat, $r_scat_d, '', 'category_id', "style='width:100%;'");
		$o_searchcat = new SearchCat($category_id = 0, $product_title = '', $cur_page = 0, $item_per_page = 10);
		$prod_search = $o_searchcat->display();

		$prod_entry_row="
		<tr id='prod_entry_inputrow'>
			<td width='$td_width'>".__("Purchase Products").__(":")." ".__("*")."</td>
			<td>".__("Browse Products").":<br />
				<table class='prod-mini-list'>
					<tr class='pml_body'>
						<td>".__("Category").":</td>
						<td>$cat_select</td>
					</tr>
					<tr class='pml_body'>
						<td>".__("Search").":</td>
						<td><input type='text' name='prod_search' value='' style='width:100%;' /></td>
					</tr>
					<tr class='pml_body'>
						<td colspan='2' class='center'><input type='button' name='btn_prod_search' value='".__("Search")."' /></td>
					</tr>
				</table><br />
				<div id='prod_search_div'>$prod_search</div>
				<p>".__("To purchase the products, browse from the product list above and click to add.")."</p>
				<table class='package-prod-list' id='pprod-list'>
					<tr class='ppl_header'>
						<td></td>
						<td>".__("Reference No.")."</td>
						<td>".__("Quantity")."</td>
					</tr>
					$prod_list
				</table>
			</td>
		</tr>";
	}
	//choose pickup location row
	if($_GET["type"]=="edit"){
		if($r_sale["stockist_sale"] == 'y'){
			$this_stockist = get_stockist_detail_by_id($r_sale['ssid']);
			$purchase_from=__("Stockist ID").__(":")." $this_stockist[sid], $this_stockist[name]<br />\n$r_sale[collect_address]".($r_sale['collect_city']? "<br />\n$r_sale[collect_city]" : '').($r_sale['collect_zip']? "<br />\n$r_sale[collect_zip], " : "").($r_sale['collect_state']? "$r_sale[collect_state]" : "")."<br />\n".$r_country_d[$r_sale["collect_country"]];
		}else{
			$purchase_from=$r_sale['mail_type'] == 'cr'? __("Courier") : __("Headquater");
		}
	}
	$purchase_from_row="
		<tr id='prod_entry_inputrow'>
			<td>".__("Pickup Location").__(":").($get_s['type'] == 'add'? " ".__("*") : '')."</td>
			<td>
				".($_GET["type"]=="edit"? $purchase_from : $purchase_from_select)."
			</td>
		</tr>";

	$member_sales=($errmsg || $msg?
	"$errmsg $msg" : "")."
	<form name='sale_form' method='post' action='$this_file?$_SERVER[QUERY_STRING]' enctype='multipart/form-data'>
	<input type='hidden' name='__req' value='1' />
	<input type='hidden' name='back_url' value=\"$back_url\" />
	<table class='amt_table'>
		<tr>
			<td colspan='2' class='center' style='padding:20px 0 20px 0;'>
			<input type='button' value='Back' onclick=\"location='$back_url';\">&nbsp;&nbsp;&nbsp;
			<input type='submit' name='submit_btn' value=\"".($_GET["type"]=="edit"? __("Update Member Sale") : __("Preview"))."\" />".($_GET['type']=='edit'? "&nbsp;&nbsp;&nbsp;
			<input type='button' name='print_invoice' value=\"".__("Print Invoice")."\" />" : "")."
			</td>
		</tr>
		<tr class='amt_header'>
			<td colspan='2'>".__("Sales Information")."</td>
		</tr>".($_GET["type"]=="edit"? "
		<tr>
			<td width='$td_width'>".__("Sale ID").__(":")."</td>
			<td>$r_sale[refno]</td>
		</tr>" : "")."
		<tr>
			<td width='$td_width'>".__("Member Sale").__(":").($get_s['type'] == 'add'? " ".__("*") : '')."</td>
			<td>$member_sale_select</td>
		</tr>
	</table>
	<div id='member_sale_y'".($dis['member_sale'] != 'y'? " class='none'" : '').">
	<table class='amt_table'>
		$form_inputfield[uid]
	</table>
	</div>
	<div id='member_sale_n'".($dis['member_sale'] == 'y'? " class='none'" : '').">
	<table class='amt_table'>
		$form_inputfield[nm_name]
		$form_inputfield[nm_contact]
	</table>
	</div>
	<table class='amt_table'>
		$prod_entry_row
		$purchase_from_row
		<tr>
			<td>".__("Payment Type").__(":").($get_s['type'] == 'add'? " ".__("*") : '')."</td>
			<td>$payment_type_select</td>
		</tr>
		$form_inputfield[delivery_cost]".($get_s['type'] == 'add'? "
		<tr>
			<td>".__("Purchase Cost").__(":")."</td>
			<td><p class='center'><input type='button' name='calc_prod_cost' value=\"".__("Calculate Cost")."\" /></p>
				<div id='prod_cost'></div>
			</td>
		</tr>" : "")."
		<tr>
			<td>".__("Collected").__(":")." ".__("*")."</td>
			<td>$collected_select<br />\n".__("Whether the product(s) of this sale is already collected by the member.")."</td>
		</tr>
		$form_inputfield[collected_date]
		$form_inputfield[remark]".($_GET["type"]=="edit"? "
		<tr>
			<td>".__("Status").__(":")." ".__("*")."</td>
			<td>$status_select</td>
		</tr>" : "")."
		<tr>
			<td colspan='2' class='center' style='padding:20px 0 20px 0;'>
			<input type='button' value='Back' onclick=\"location='$back_url';\">&nbsp;&nbsp;&nbsp;
			<input type='submit' name='submit_btn' value=\"".($_GET["type"]=="edit"? __("Update Member Sale") : __("Preview"))."\" />".($_GET['type']=='edit'? "&nbsp;&nbsp;&nbsp;
			<input type='button' name='print_invoice' value=\"".__("Print Invoice")."\" />" : "")."
			</td>
		</tr>
	</table>
	</form>";
}

$content="<h2>$page_title</h2>$member_sales";

print format_admin_page($content, $this_title, $css.$jvscript);
?>